import qs from 'qs'
import axios from 'axios'
import store from "@/store";
import {translateApi} from "@/api/website/inform";

/**
 * @description 翻译
 * */
function translate(text, source, target) {
  if (!text) return;
  if (store.getters.translate === 'google') { // 谷歌翻译
    return new Promise((resolve) => {
      axios({
        method: "get",
        url: 'https://translate.googleapis.com/translate_a/single',
        params: {
          client: 'gtx',
          dt: 't',
          sl: source,
          tl: target,
          q: text
        },
        paramsSerializer: params => qs.stringify(params)
      })
        .then(result => {
          resolve(result.data[0][0][0])
        })
        .catch(() => { // 谷歌翻译失败转阿里翻译
          store.dispatch('setTranslate', 'alibaba');
          let param = {text, source, target}
          translateApi(param)
            .then(result => {
              let response = JSON.parse(result.resultParam.translate);
              resolve(response.translated)
            })
            .catch(() => {
              resolve('')
            })
        })
    });
  } else { // 阿里翻译
    return new Promise((resolve) => {
      let param = {text, source, target}
      translateApi(param)
        .then(result => {
          let response = JSON.parse(result.resultParam.translate);
          resolve(response.translated)
        })
        .catch(() => {
          resolve('')
        })
    })
  }
}

// 中文 -> 英文
export function translateZhToEn(text) {
  return translate(text, 'zh', 'en')
}

// 中文 -> 老挝
export function translateZhToLaos(text) {
  return translate(text, 'zh', 'lo')
}

// 老挝 -> 中文
export function translateLaosToZh(text) {
  return translate(text, 'lo', 'zh')
}

// 老挝 -> 英文
export function translateLaosToEn(text) {
  return translate(text, 'lo', 'en')
}
